<template>
  <a-spin :spinning="confirmLoading">
    <div>
      <a-form-model ref="form" slot="detail" :model="model" :rules="validatorRules">
        <a-row>
          <a-col :span="24">
            <a-form-model-item
              label="父节点"
              :label-col="labelCol"
              :wrapper-col="wrapperCol"
              prop="parentId"
              :validate-status="validateStatus"
            >
              <a-tree-select
                v-model="model.parentId"
                style="width: 100%"
                :dropdown-style="{ maxHeight: '200px', overflow: 'auto' }"
                :tree-data="treeData"
                placeholder="请选择父级分类"
                :treeDefaultExpandedKeys="treeDefaultExpandedKeys"
                @change="handleParentIdChange"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="名称" :label-col="labelCol" :wrapper-col="wrapperCol" prop="name">
              <a-input v-model="model.name" placeholder="请输入名称" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="编码前缀" :label-col="labelCol" :wrapper-col="wrapperCol" prop="prefix">
              <a-input v-model="model.prefix" placeholder="请输入编码前缀" />
            </a-form-model-item>
          </a-col>
           <a-col :span="24">
            <a-form-model-item label="编码流水号时间格式" :label-col="labelCol" :wrapper-col="wrapperCol" prop="fileNoDateFormat">
            
              <a-select v-model="model.fileNoDateFormat"  style="width: 100%"  placeholder="流水号时间格式默认年月日">
                <a-select-option v-for="(d, index) in fileNoDateFormatOptions" :key="index" :value="d.value">
                  {{ d.label }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="大类权限" :label-col="labelCol" :wrapper-col="wrapperCol" prop="authorityArr">
              <a-select v-model="model.authorityArr" mode="multiple" style="width: 100%" placeholder="请选择权限">
                <a-select-option v-for="(d, index) in authorityOptions" :key="index" :value="d.value">
                  {{ d.label }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <!--          <a-col :span="24">-->
          <!--            <a-form-model-item label="发布范围" :label-col="labelCol" :wrapper-col="wrapperCol" prop="publishWay">-->
          <!--              <j-multi-select-tag-->
          <!--                v-model="model.publishWay"-->
          <!--                :options="publishWayOptions"-->
          <!--                placeholder="请选择发布方式"-->
          <!--              />-->
          <!--            </a-form-model-item>-->
          <!--          </a-col>-->
          <a-col :span="24">
            <a-form-model-item label="是否审批" :label-col="labelCol" :wrapper-col="wrapperCol" prop="autoPublish">
              <a-switch v-model="model.autoPublish" checked-children="是" un-checked-children="否" />
            </a-form-model-item>
          </a-col>
          <!--          <a-col :span="24">-->
          <!--            <a-form-model-item label="是否公开" :label-col="labelCol" :wrapper-col="wrapperCol" prop="openFlag">-->
          <!--              <a-switch v-model="model.copenFlag" checked-children="是" un-checked-children="否" />-->
          <!--            </a-form-model-item>-->
          <!--          </a-col>-->
          <!--          <a-col :span="24">-->
          <!--            <a-form-model-item label="所属部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="defaultDept">-->
          <!--              <a-input-number v-model="model.defaultDept" placeholder="请输入所属部门" style="width: 100%" />-->
          <!--            </a-form-model-item>-->
          <!--          </a-col>-->
          <a-col :span="24">
            <a-form-model-item label="管理员" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-select
                v-model="model.manager"
                mode="multiple"
                label-in-value
                placeholder="输入名称查找用户"
                style="width: 100%"
                :filter-option="false"
                :not-found-content="fetching ? '找不到记录' : '找不到记录'"
                @search="fetchUser"
                @change="handleChange"
              >
                <a-spin v-if="fetching" slot="notFoundContent" size="small" />
                <a-select-option v-for="(d, index) in userData" :key="index" :value="d.username">
                  {{ d.realname }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <!-- <a-col :span="24">
            <a-form-model-item label="可否二级发布" :label-col="labelCol" :wrapper-col="wrapperCol" prop="releaseFlag">
              <a-switch v-model="model.releaseFlag" checked-children="是" un-checked-children="否" />
            </a-form-model-item>
          </a-col> -->
        </a-row>
      </a-form-model>
    </div>
  </a-spin>
</template>

<script>
  import { httpAction, getAction } from '@/api/manage';
  import { postAction } from '../../../api/manage';
  import debounce from 'lodash/debounce'
  export default {
    name: 'HteFileClassForm',
    components: {},
    props: {
      // 表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      },
      // 顶级分类
      parentId: {
        type: String,
        default: null,
        required: true
      }
    },
    data() {
      this.fetchUser = debounce(this.fetchUser, 800)
      return {
        publishWayOptions: [
          { value: '1', label: '私有组' },
          { value: '2', label: '发送人员' }
        ],
        authorityOptions: [
          { value: '1', label: '查阅' },
          { value: '2', label: '编辑' },
          { value: '3', label: '下载' },
          { value: '4', label: '可废除' },
          { value: '6', label: '可分享' }
        ],
        fileNoDateFormatOptions:[
          { value: 'yy', label: '年（格式示例：21）' },
          { value: 'yyyy', label: '年（格式示例：2021）' },
          { value: 'yyyyMM', label: '年月（格式示例：202108）' },
          { value: 'yyyyMMdd', label: '年月日（格式示例：20210830）' },
        ],
        treeData: [],
        validateStatus: '',
        model: { autoPublish: false },
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        confirmLoading: false,
        validatorRules: {
          autoPublish: [{ required: true, message: '请输入自动发布,0:需要审批 1:不需要!' }],
          name: [{ required: true, message: '请输入分类名称' }],
          prefix: [{ required: true, message: '请输入编码前缀' }],
          authorityArr: [{ required: true, message: '请选择权限' }]
        },
        userData: [],
        fetching: false,
        url: {
          add: '/lib/hteFileClass/add',
          edit: '/lib/hteFileClass/edit',
          queryById: '/lib/hteFileClass/queryById',
          getTreeList: '/lib/hteFileClass/getTreeList',
          getUserList: '/lib/hteFileClass/getUserList'
        },
        treeDefaultExpandedKeys:[],
      };
    },
    computed: {
      formDisabled() {
        return this.disabled;
      }
    },
    created() {
      // 备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
    },
    methods: {
      add() {
        this.visible = true;
        this.loadTree();
      },
      edit(record) {
        console.log(record);

        this.model = Object.assign({}, record);
        this.$set(this.model, 'manager', []);
        // this.model.managerId={key: "liangyh", label: '领就的'}
        this.visible = true;
        this.loadFileClass(record.id);
        this.loadTree();
      },
      loadTree() {
        var that = this;
        getAction(this.url.getTreeList, { parentId: this.parentId }).then(res => {
          if (res.success) {
            console.log(res);
            that.treeData = res.result.treeList;
            that.treeData.forEach(node => {
              node.selectable = true;
            });
            // let treeList = res.result.treeList
            // for(let a=0;a<treeList.length;a++){
            //     let temp = treeList[a];
            //     that.treeData.push(temp);
            // }
            var treeDefaultExpandedKeys = [that.treeData[0].key]
            this.treeDefaultExpandedKeys = treeDefaultExpandedKeys
          }
        });
      },
      loadFileClass(id) {
        const that = this;
        getAction(this.url.queryById, { id: id }).then(res => {
          if (res.success) {
            that.model = res.result;
            that.model.manager = that.model.manager || [];
            if( that.model.authority) {
              that.$set(that.model,'authorityArr',that.model.authority.split(','))
            }
          }
        });
      },
      submitForm() {
        const that = this;
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.confirmLoading = true;
            let httpurl = '';
            if (!this.model.id) {
              httpurl += this.url.add;
            } else {
              httpurl += this.url.edit;
            }
            if (this.model.manager) {
              let managerId = '';
              this.model.manager.forEach(it => {
                managerId += it.key + ',';
              });
              this.model.managerId = managerId;
            }
            if( this.model.authorityArr) {
              that.$set(that.model,'authority',that.model.authorityArr.join(','))
            }
            postAction(httpurl, this.model)
                .then(res => {
                  if (res.success) {
                    that.$message.success(res.message);
                    that.$emit('ok');
                  } else {
                    that.$message.warning(res.message);
                  }
                })
                .finally(() => {
                  that.confirmLoading = false;
                });
          }
        });
      },
      handleParentIdChange(value) {
        if (!value) {
          this.validateStatus = 'error';
        } else {
          this.validateStatus = 'success';
        }
      },
      fetchUser(val) {
        this.userData = [];
        this.fetching = true;
        if(!val || !val.trim()){return }
        getAction(this.url.getUserList, { name: val.trim() }).then(res => {
          if (res.success) {
            console.log(res);
            this.userData = res.result;
            this.fetching = false;
          }
        });
      },
      handleChange(value) {
        console.log(value);
        console.log(this.model.managerId);
      }
    }
  };
</script>
